package top.maof.book.controller;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.maof.book.annotation.Hot;
import top.maof.book.aspect.HotAspect;
import top.maof.book.model.Forward;
import top.maof.book.result.Result;
import top.maof.book.service.BookInfoService;
import top.maof.book.service.ForwardService;
import top.maof.book.utils.JWTUtils;

@RequestMapping("/forward")
@RestController
public class ForwardController {

    @Autowired
    BookInfoService bookInfoService;

    @Autowired
    ForwardService forwardService;

    @ApiOperation("用户对此书是否转发过")
    @GetMapping("/isExit")
    public Result has(@RequestHeader("token") String token, Integer bookId){
        Integer userId = Integer.parseInt(JWTUtils.parseToken(token, "id"));
        return forwardService.isExist(userId, bookId) ? Result.success(true) : Result.success(false);
    }

    @ApiOperation("用户转发")
    @RequestMapping("/addProfile")
    public Result add(@RequestHeader("token") String token, Integer bookId){
        Integer userId = Integer.parseInt(JWTUtils.parseToken(token, "id"));
        boolean isSuccess;
        if(forwardService.isExist(userId, bookId)){
            isSuccess = forwardService.addNum(userId, bookId);
        }else{
            Forward forward = new Forward();
            forward.setUserId(userId);
            forward.setBookId(bookId);
            forward.setNum(1);
            forward.setTime(System.currentTimeMillis());
            isSuccess = forwardService.save(forward);
        }
        isSuccess = isSuccess && bookInfoService.addForward(bookId, 1);
        return isSuccess ? Result.success() : Result.response_500();
    }

    @RequestMapping("/forwardNum")
    @ApiOperation("书的转发次数")
    public Result bookForwardNum(Integer bookId){
        return Result.success(forwardService.forwardNum(bookId));
    }




}
